package com.xcx.services.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xcx.bo.CommUserInfo;
import com.xcx.bo.CommUserInfoExample;
import com.xcx.common.dto.base.BaseResp;
import com.xcx.common.dto.req.QueryUserBindingReq;
import com.xcx.common.dto.req.SaveUserInfoReq;
import com.xcx.common.dto.req.UserLoginReq;
import com.xcx.common.dto.resp.QueryUserBindingResp;
import com.xcx.common.dto.resp.UserLoginResp;
import com.xcx.common.enums.IsExistEnum;
import com.xcx.common.enums.RespCodeEnum;
import com.xcx.common.exceptions.CommonException;
import com.xcx.common.services.common.CommUserService;
import com.xcx.common.utils.CheckParamUtils;
import com.xcx.common.utils.ExceptionUtils;
import com.xcx.common.utils.IdGenUtils;
import com.xcx.common.utils.JsonUtils;
import com.xcx.dao.CommUserInfoDao;
import com.xcx.remote.WxUserRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 *
 * @author yangjun
 * @date 2018年7月14日 下午11:42:52
 */
@Slf4j
@Service
public class CommUserServiceImpl implements CommUserService {

    @Autowired
    private CommUserInfoDao commUserInfoDao;

    @Autowired
    private WxUserRemoteService wxUserRemoteService;


    @Override
    public UserLoginResp userLogin(UserLoginReq userLoginReq) {
        log.info("userLogin req:{}", userLoginReq.toString());
        UserLoginResp baseResp = new UserLoginResp();
        try {
            CheckParamUtils.validateReqGson(userLoginReq);
            String WxUserJson = wxUserRemoteService.userAuthorizeLogin(userLoginReq.getAppId(), userLoginReq.getSecret(), userLoginReq.getWxCode());
            if (StringUtils.isBlank(WxUserJson)) {
                throw new CommonException(RespCodeEnum.USER_WX_AUTHORIZE_LOGIN_FAIL);
            }
            Map<String, String> WxUserMap = JsonUtils.parse(WxUserJson);
            CommUserInfoExample example = new CommUserInfoExample();
            example.createCriteria().andWxOpenIdEqualTo(WxUserMap.get("openid"))
                    .andProductCodeEqualTo(userLoginReq.getProductCode());
            List<CommUserInfo> commUserInfoList = commUserInfoDao.selectByExample(example);
            if (CollectionUtils.isEmpty(commUserInfoList)) {
                CommUserInfo commUserInfo = new CommUserInfo();
                commUserInfo.setUserNo(IdGenUtils.uuid());
                commUserInfo.setProductCode(userLoginReq.getProductCode());
                commUserInfo.setWxOpenId(WxUserMap.get("openid"));
                commUserInfo.setWxSessionKey(WxUserMap.get("session_key"));
                commUserInfo.setWxUnionId(WxUserMap.get("unionid"));
                commUserInfoDao.insertSelective(commUserInfo);
                baseResp.setUserNo(commUserInfo.getUserNo());
            } else {
                baseResp.setUserNo(commUserInfoList.get(0).getUserNo());
            }
            baseResp.buildDefaultSuccessResp(userLoginReq);
            baseResp.setOpenId(WxUserMap.get("openid"));
            baseResp.setSessionKey(WxUserMap.get("session_key"));
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("CommUserServiceImpl", null, baseResp, e.getMessage(), e);
        }
        log.info("userLogin.resp:{}", baseResp.toString());
        return baseResp;
    }

    @Override
    public QueryUserBindingResp queryUserBinding(QueryUserBindingReq queryUserBindingReq) {
        log.info("queryUserBinding req:{}", queryUserBindingReq.toString());
        QueryUserBindingResp baseResp = new QueryUserBindingResp();
        try {
            CheckParamUtils.validateReqGson(queryUserBindingReq);
            baseResp.setUserFlag(IsExistEnum.EXIST_NO.getCode());
            baseResp.setUserBaseInfoFlag(IsExistEnum.EXIST_NO.getCode());
            baseResp.setUserMobileFlag(IsExistEnum.EXIST_NO.getCode());
            baseResp.setUserDeviceInfoFlag(IsExistEnum.EXIST_NO.getCode());
            CommUserInfoExample example = new CommUserInfoExample();
            example.createCriteria().andUserNoEqualTo(queryUserBindingReq.getUserNo())
                    .andProductCodeEqualTo(queryUserBindingReq.getProductCode());
            List<CommUserInfo> commUserInfoList = commUserInfoDao.selectByExample(example);
            if (CollectionUtils.isNotEmpty(commUserInfoList)) {
                CommUserInfo commUserInfoObj = commUserInfoList.get(0);
                baseResp.setUserFlag(IsExistEnum.EXIST_YES.getCode());
                if (StringUtils.isNotBlank(commUserInfoObj.getNickname())) {
                    baseResp.setUserBaseInfoFlag(IsExistEnum.EXIST_YES.getCode());
                }
                if (StringUtils.isNotBlank(commUserInfoObj.getMobile())) {
                    baseResp.setUserMobileFlag(IsExistEnum.EXIST_YES.getCode());
                }
                if (StringUtils.isNotBlank(commUserInfoObj.getDeviceInfo())) {
                    baseResp.setUserDeviceInfoFlag(IsExistEnum.EXIST_YES.getCode());
                }
            }
            baseResp.buildDefaultSuccessResp(queryUserBindingReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("CommUserServiceImpl", null, baseResp, e.getMessage(), e);
        }
        log.info("queryUserBinding.resp:{}", baseResp.toString());
        return baseResp;

    }

    @Override
    public BaseResp saveUserInfo(SaveUserInfoReq saveUserInfoReq) {
        log.info("saveUserInfo req:{}", saveUserInfoReq.toString());
        BaseResp baseResp = new BaseResp();
        try {
            CheckParamUtils.validateReqGson(saveUserInfoReq);
            CommUserInfoExample example = new CommUserInfoExample();
            example.createCriteria().andUserNoEqualTo(saveUserInfoReq.getUserNo())
                    .andProductCodeEqualTo(saveUserInfoReq.getProductCode());
            List<CommUserInfo> commUserInfoList = commUserInfoDao.selectByExample(example);
            if (CollectionUtils.isEmpty(commUserInfoList)) {
                CommUserInfo commUserInfo = new CommUserInfo();
                commUserInfo.setUserNo(IdGenUtils.uuid());
                commUserInfo.setProductCode(saveUserInfoReq.getProductCode());
                commUserInfo.setWxOpenId(saveUserInfoReq.getWxOpenId());
                commUserInfo.setNickname(saveUserInfoReq.getNickname());
                commUserInfo.setUserAvatarUrl(saveUserInfoReq.getUserAvatarUrl());
                commUserInfo.setUserSex(saveUserInfoReq.getUserSex());
                commUserInfo.setMobile(saveUserInfoReq.getMobile());
                commUserInfo.setCountry(saveUserInfoReq.getCountry());
                commUserInfo.setProvince(saveUserInfoReq.getProvince());
                commUserInfo.setCity(saveUserInfoReq.getCity());
                commUserInfo.setDeviceInfo(saveUserInfoReq.getDeviceInfo());
                commUserInfoDao.insertSelective(commUserInfo);
            } else {
                CommUserInfo commUserInfo = commUserInfoList.get(0);
                commUserInfo.setProductCode(saveUserInfoReq.getProductCode());
                commUserInfo.setNickname(saveUserInfoReq.getNickname());
                commUserInfo.setUserAvatarUrl(saveUserInfoReq.getUserAvatarUrl());
                commUserInfo.setUserSex(saveUserInfoReq.getUserSex());
                commUserInfo.setMobile(saveUserInfoReq.getMobile());
                commUserInfo.setCountry(saveUserInfoReq.getCountry());
                commUserInfo.setProvince(saveUserInfoReq.getProvince());
                commUserInfo.setCity(saveUserInfoReq.getCity());
                commUserInfo.setDeviceInfo(saveUserInfoReq.getDeviceInfo());
                commUserInfoDao.updateByPrimaryKeySelective(commUserInfo);
            }
            baseResp.buildDefaultSuccessResp(saveUserInfoReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("CommUserServiceImpl", null, baseResp, e.getMessage(), e);
        }
        log.info("saveUserInfo.resp:{}", baseResp.toString());
        return baseResp;
    }
}
